package cn.txun.csmall.gateway.filters;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.function.Supplier;

/**
 * 网关过滤器必须实现一个接口GlobalFilter
 * 如果想定义多个过滤器执行顺序
 * 还有实现接口Ordered
 */
@Slf4j
@Component
public class MyFilter04 implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("MyFilter04.filter方法执行了");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //通过request对象获取参数
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        List<String> list = queryParams.get("name");
        //判断参数是否存在，如果不存在，则拦截这个请求，返回自定义响应数据
        if(list==null || list.size()==0){
            //定义当前写出数据的格式，添加一个响应头
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            //把响应数据(比如JsonResult字符串)封装在response中
            //封装一个写好响应数据的Mono对象作为返回值
            return response.writeWith(Mono.fromSupplier(new Supplier<DataBuffer>() {
                @Override
                public DataBuffer get() {
                    return response.bufferFactory().wrap("你好，没有携带name".getBytes(StandardCharsets.UTF_8));
                }
            }));
        }else{
            log.info("携带了name:{}",list.get(0));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -5;
    }
}
